import { asyncRoutes, constantRoutes } from '@/router'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
// function hasPermission(roles, route) {
//   if (route.meta && route.meta.roles) {
//     return roles.some(role => route.meta.roles.includes(role))
//   } else {
//     return true
//   }
// }
const roleList = {
  '行政部': [
    { path: '/' },
    { path: '/dashboard' },
    { path: '/profile' },
    { path: '/profile/index' },
    { path: '/house' },
    { path: '/house/index' },
    { path: '/users' },
    { path: '/users/index' },
    { path: '/staff' },
    { path: '/staff/index' },
    { path: '/staff/add' },
    { path: '/staff/change' }
  ],
  '维修部': [
    { path: '/' },
    { path: '/dashboard' },
    { path: '/profile' },
    { path: '/profile/index' },
    { path: '/orders' },
    { path: '/orders/index' },
    { path: '/orders/addOrders' }
  ],
  '业务部': [
    { path: '/' },
    { path: '/dashboard' },
    { path: '/profile' },
    { path: '/profile/index' },
    { path: '/news' },
    { path: '/news/index' },
    { path: '/news/add' },
    { path: '/messages' },
    { path: '/messages/index' },
    { path: '/messages/reply' },
    { path: '/messages/addMessage' },
    { path: '/bills' },
    { path: '/bills/index' },
    { path: '/bills/addBills' },
    { path: '/orders' },
    { path: '/orders/index' },
    { path: '/orders/addOrders' }
  ]
}
/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const accessedRoutes = []
  routes.forEach(route => {
    const tmp = {}
    if (roles.some(a => a.path === route.path)) {
      for (const key in route) {
        if (Object.prototype.hasOwnProperty.call(route, key)) {
          if (key !== 'children') {
            tmp[key] = route[key]
          } else if (key === 'children') {
            const tmpC = filterAsyncRoutes(route[key], roles)
            tmpC.length > 0 && (tmp.children = tmpC)
          }
        }
      }
    }
    tmp.path && accessedRoutes.push(tmp)
  })
  return accessedRoutes
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
    state.routes.push({ path: '*', redirect: '/404', hidden: true })
  }
}

const actions = {
  generateRoutes({ commit }, role) {
    return new Promise(resolve => {
      let accessedRoutes
      if (role === 'admin') {
        accessedRoutes = asyncRoutes || []
      } else {
        const roles = roleList[role]
        console.log(role, roles)
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
